using Application.Abstractions.Authentication;
using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Todos;
using Microsoft.EntityFrameworkCore;
using SharedKernel;

namespace Application.Todos.Update;

internal sealed class UpdateTodoCommandHandler(
    IApplicationDbContext context,
    ICurrentUser currentUser)
    : ICommandHandler<UpdateTodoCommand>
{
    public async ValueTask<Result> Handle(UpdateTodoCommand command, CancellationToken cancellationToken)
    {
        TodoItem? todoItem = await context.TodoItems
            .SingleOrDefaultAsync(t => t.Id == command.TodoItemId && t.UserId == currentUser.UserId, cancellationToken);

        if (todoItem is null)
        {
            return Result.Failure(TodoItemErrors.NotFound(command.TodoItemId));
        }

        // 使用领域方法更新属性
        todoItem.UpdateDescription(command.Description);
        todoItem.UpdatePriority(command.Priority);
        todoItem.UpdateDueDate(command.DueDate);
        
        if (command.Labels is not null)
        {
            todoItem.SetLabels(command.Labels);
        }

        await context.SaveChangesAsync(cancellationToken);

        return Result.Success();
    }
}